package com.yupi.generator;

import com.yupi.model.MainTemplateConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class DynamicGenerator {

    public static void main(String[] args) throws Exception {
        String inputPath = "yuzi-generator-basic/src/main/resources/templates";
        String outputPath = "MainTemplate.java";
        //3. 指定数据
        MainTemplateConfig mainTemplateConfig = new MainTemplateConfig();
        mainTemplateConfig.setAuthor("zwl");
        mainTemplateConfig.setLoop(true);
        mainTemplateConfig.setOutputText("haha");
        doGenerate(inputPath,outputPath,mainTemplateConfig);
    }

    /**
     * 生成文件
     * @param inputPath 模板文件输入路径
     * @param outputPath  输出路径
     * @param model 数据模型
     * @throws IOException
     * @throws TemplateException
     */
    private static void doGenerate(String inputPath,String outputPath,Object model) throws IOException, TemplateException {
        //1. 先new出配置类
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);
        //2. 指定模板文件路径
        configuration.setDirectoryForTemplateLoading(new File(inputPath));
        configuration.setDefaultEncoding("UTF-8");

        Template template = configuration.getTemplate("MainTemplate.java.ftl");

        //3. 指定数据
        MainTemplateConfig mainTemplateConfig = new MainTemplateConfig();
        mainTemplateConfig.setAuthor("zwl");
        mainTemplateConfig.setLoop(true);
        mainTemplateConfig.setOutputText("haha");
        //4. 指定生成文件
        Writer fileWriter = new FileWriter(outputPath);

        //5. 生成
        template.process(model,fileWriter);
        fileWriter.close();
    }
}
